package com.linghu.springcloud.controller;


import com.linghu.springcloud.bean.Member;
import com.linghu.springcloud.bean.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author 令狐荣豪
 * @version 1.0
 */
@RestController
@Slf4j
public class MemberConsumerController {
    public static final String
//        MEMBER_SERVICE_PROVIDER="http://localhost:10001";
        MEMBER_SERVICE_PROVIDER="http://MEMBER-SERVICE-PROVIDER";

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private DiscoveryClient discoveryClient;

    @GetMapping("/member/consumer/discovery")
    public Object discovery(){
        List<String> services = discoveryClient.getServices();
        for (String element :services) {
            System.out.println("======== 服 务 名 " + element +
                    "=======================");
            List<ServiceInstance> instances = discoveryClient.getInstances(element);
            for (ServiceInstance instance :instances) {
                System.out.println(instance.getServiceId()+"\t"+instance.getHost()
                +"\t"+instance.getPort()+"\t"+instance.getUri());
            }

        }
        return this.discoveryClient;
    }

    @PostMapping("/member/consumer/save")
    @ResponseBody
    public Result<Member> save(@RequestBody Member member){
       return restTemplate.postForObject(MEMBER_SERVICE_PROVIDER+"/member/save"
               ,member,Result.class);

    }

    @GetMapping("/member/consumer/get/{id}")
    public Result<Member> getMemberById(@PathVariable("id") Long id){
       return restTemplate.getForObject(MEMBER_SERVICE_PROVIDER+"/member/get/"+id
               ,Result.class);
    }
}
